<template>
  <div class="affix-container">
    <zh-space style="padding-top: 10px">
      <zh-card >
        <zh-form ref="apiQueryForm" :model="state.queryParam" :rules="rules">
          <zh-form-input prop="funcCode" label="功能编号" placeholder="支持模糊查询"
                         v-model="state.queryParam.funcCode"></zh-form-input>
          <zh-form-input prop="funcTitle" label="功能标题" placeholder="支持模糊查询"
                         v-model="state.queryParam.funcTitle"></zh-form-input>
          <zh-form-select
              prop="funcType"
              label="功能类型"
              :options="state.dictData.funcType"
              placeholder="请选择"
              v-model="state.queryParam.funcType"
          ></zh-form-select>

          <zh-form-select
              prop="funcSourceType"
              label="功能来源类型"
              :options="state.dictData.funcSourceType"
              placeholder="请选择"
              v-model="state.queryParam.funcSourceType"
          ></zh-form-select>

          <zh-form-query v-model="state.advanced"  :form-ref="apiQueryForm" @queryClick="clearData"
                         :table-ref="apiTable"></zh-form-query>
        </zh-form>
      </zh-card>
      <zh-table
          ref="apiTable"
          title=""
          :height="600"
          funcCode="function0001"
          :columns="state.tableColumn"
          @radio-change="radioChangeEvent"
          :radio-config="{ trigger: 'row' }"
          :disabled="false"
          highlight-current-row
          @current-change="handleCurrentChange"
      >
        <template #header_button>
          <zh-button style="margin-left: 8px" button-type="edit" @click="apiDesigner">编排设计
          </zh-button>
          <zh-button style="margin-left: 8px" button-type="add" @click="apiRegister">接口注册
          </zh-button>
          <zh-button style="margin-left: 8px" v-if="state.infoFlag" icon="ele-Refresh" type="warning"
                     @click="clearApiCache">清除缓存
          </zh-button>
          <zh-button style="margin-left: 8px" v-if="state.infoFlag" icon="ele-Refresh" type="warning"
                     @click="reloadflow">编排热刷新</zh-button>
        </template>
        <template #status_edit="{ row }">
          <el-switch
              v-model="row.funcStatus"
              active-text="启用"
              inactive-text="禁用"
              active-value="1"
              inactive-value="0"
              inline-prompt
              size="large"
              @change="onStatusChange(row)"
              :width="60"
          ></el-switch>
        </template>
        <template #op="scope">
          <el-tooltip content="编辑" placement="top">
                    <span>
                        <zh-button button-type="edit" link @click="editApi(scope.row)">编辑</zh-button>
                    </span>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
                    <span>
                        <zh-button button-type="del" link @click="deleteApi(scope.row)">删除</zh-button>
                    </span>
          </el-tooltip>
        </template>
      </zh-table>

    </zh-space>
    <el-dialog
        ref="dialog"
        v-model="state.dialogVisible"
        title="功能信息"
        width="80%"
    >
      <api-info ref="apiInfoPage" :display-flag="false"></api-info>
    </el-dialog>

    <zh-dialog title="接口注册"    width="80%" v-model="state.registerVisible">
      <!-- 使用子组件 -->
      <ApiRegister ref="apiRegisterPage" @close="close" :display="false"/>
      <template #footer>
                <span class="dialog-footer">
                    <zh-button @click="state.registerVisible = false">取消</zh-button>
                    <zh-button type="primary" @click="saveRegister"> 保存 </zh-button>
                </span>
      </template>
    </zh-dialog>

  </div>
</template>

<script lang="ts" setup name="apiManagerIndex">
import { useRouter } from 'vue-router';
import {ElMessageBox} from "element-plus";
import ApiInfo from '@/views/apiCenter/ApiManager/component/ApiInfo.vue';
import ApiRegister from '@/views/apiCenter/ApiRegister/index.vue'

//-----------------定义组件--------------
const apiQueryForm = ref<any>({});
const apiTable = ref<any>({});
const apiInfoPage = ref();
const apiRegisterPage = ref();
//-----------------定义参数---------------
const router = useRouter();

const state = reactive({
  registerVisible:false,
  //查询条件
  queryParam: {} as any,
  dictData: {},
  advanced:true,
  funcId: '',
  selectRow: {
  },
  apiInfo: null as any,
  selectNode: {} as any,
  //弹窗
  infoFlag: true,
  dialogVisible: false,
  tableColumn: [
    {
      type: 'radio',
      width: 50,
      fixed: 'left',
      align: 'center',
    },
    {type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号'},
    {field: 'funcId', title: '方法Id', fixed: 'left', visible: false, align: 'center', width: 150},
    {field: 'funcCode', title: '功能编号', align: 'center', fixed: 'left', width: 150},
    {field: 'funcTitle', title: '功能名称', align: 'center', fixed: 'left', width: 150},
    {field: 'funcTypeName', title: '功能类型', align: 'center',  width: 150},
    //服务名 SERVICE_NAME
    {field: 'serviceName', title: '服务名', align: 'center',  width: 200},
    {field: 'visits', title: '每日访问上限次数', align: 'center',  width: 150},
    {
      field: 'funcStatus',
      title: '状态',
      align: 'center',
      editRender: {},
      slots: {
        // 使用插槽模板渲染
        default: 'status_edit',
        edit: 'status_edit',
      },
      width: 120,
    },
    {field: 'funcDesc', title: '功能描述', align: 'center',  width: 300},
    {field: 'funcSourceTypeName', title: '功能来源', align: 'center',  width: 120},
    {field: 'httpMethod', title: '调用方式', align: 'center',  width: 120},
    {field: 'timeout', title: '服务超时时间', align: 'center',  width: 120},
    { field: 'op', title: '操作', visible: true, align: 'center', width: 250, fixed: 'right', slots: { default: 'op' } },
  ],
});

const rules = reactive({
  tableId: [
    {
      required: true,
      message: '请输入表Id',
      trigger: 'blur',
    },
  ]
});

//---------------------初始化---------------------
const params = {
  dictFields: 'funcType,funcSourceType',
};
$api.common.getBatchDict.post(params).then((res) => {
  state.dictData = res.result;
});


//----------------------自定义方法-------------------

// 启用/禁用 功能/功能
function onStatusChange(row) {
  const params = {
    funcId: row.funcId,
    status: row.funcStatus,
  };
  let text = '禁用';
  if (params.status == '1') {
    text = '启用';
  }
  setTimeout(() => {
    $api.common.send
        .post('function0011', params)
        .then(() => {
          $messageBox.success(text + '成功', '提示');
        })
        .catch(() => {});
  }, 200);
}

function clearData(){
  state.funcId = '';
  state.selectRow = {};
}

//接口注册
const saveRegister =async ()=>{
  await apiRegisterPage.value.addForm();
}

const close = (e)=>{
  state.registerVisible = false;
  console.log(e,"传来的数据")
  state.queryParam.funcCode = e.funcCode;
  state.queryParam.funcTitle = e.funcTitle;
  state.queryParam.funcType = '';
  state.queryParam.funcSourceType = '';
  state.funcId = e.funcId
  //调用查询接口
  apiTable.value.query(state.queryParam);
  state.dialogVisible = true;
  nextTick(()=>{
    state.selectNode = {
      key:state.funcId
    }
    apiInfoPage.value.initInfo(state.funcId);
  });
}

function radioChangeEvent({row}) {
  state.funcId = row.funcId;
  state.selectRow = row;
}

function handleCurrentChange(row) {
  state.selectRow = row;
  state.funcId = row.funcId;
}

function apiRegister(){
  state.registerVisible = true;
}

function apiDesigner(){
  if (state.funcId) {
    if(state.selectRow.funcSourceType!='3'){
      ElMessageBox.confirm(
          '请先选择编辑接口进行编排设计',
          '提示',
          {
            confirmButtonText: '确定',
            type: 'warning',
            showCancelButton: false
          }
      ).then(() => {

      }).catch(() => {

      })
      return;
    }else{
      let params={
        "liteflowChainId":state.selectRow.liteflowChainId,
        "liteflowApplicationName":state.selectRow.serviceName,
        "liteflowChainName":state.selectRow.funcCode,
        "liteflowChainDesc":state.selectRow.funcTitle,
      }
      if(!state.selectRow.liteflowChainId){
        $api.common.send.post('LITEFLOWCHAIN0004',params)
            .then((res) => {
              router.push({name:'apiDesigner',query:{funcCode:state.selectRow.funcCode,funcTitle:state.selectRow.funcTitle,chainId:res.result.liteflowChainId,serviceName:state.selectRow.serviceName}});
            })
            .catch(() => {

            });
      }else{
        router.push({name:'apiDesigner',query:{funcCode:state.selectRow.funcCode,funcTitle:state.selectRow.funcTitle,chainId:state.selectRow.liteflowChainId,serviceName:state.selectRow.serviceName}});
      }

    }
  } else {
    ElMessageBox.confirm(
        '请先选择需要操作的功能',
        '提示',
        {
          confirmButtonText: '确定',
          type: 'warning',
          showCancelButton: false
        }
    ).then(() => {

    }).catch(() => {

    })
    return;
  }
}

function editApi(row:any) {
  state.funcId = row.funcId;
  if (state.funcId) {
    state.dialogVisible = true;
    nextTick(()=>{
      state.selectNode = {
        key:state.funcId
      }
      apiInfoPage.value.initInfo(state.funcId);
    });
  } else {
    ElMessageBox.confirm(
        '请先选择需要操作的功能',
        '提示',
        {
          confirmButtonText: '确定',
          type: 'warning',
          showCancelButton: false
        }
    ).then(() => {

    }).catch(() => {

    })
    return;
  }
}

/**编排平滑热刷新*/
function reloadflow(){
  $api.common.send.post('LITEFLOWCENTER0002')
      .then(() => {
        ElMessageBox.alert('编排平滑热刷新成功');

      })
}

function clearApiCache() {
  const params: any = {};
  if (state.apiInfo) {
    params.funcId = state.apiInfo.funcId;
  }
  setTimeout(() => {
    //function0009
    $api.common.send.post('function0009',params)
        .then(() => {
          $messageBox.success('清除缓存成功', '提示');
        })
        .catch(() => {
        });
  }, 100);
}
onMounted(() => {
  apiTable.value.query();
})

const deleteApi = (row) => {
  state.funcId = row.funcId;
  if (!state.funcId) {
    $messageBox.warning('请先选择需要删除的数据', '提示');
    return;
  }
  ElMessageBox({
    title: '删除确认',
    message: h('p', null, [
      h('span', null, '是否确定删除功能'),
      h('i', { style: 'color: teal' }, state.selectRow.funcCode),
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '正在删除...'
        deleteApiSave(instance,done);
      } else {
        done()
      }
    },
  })
}

function deleteApiSave(instance,done) {
  if (state.funcId) {
    const params = {
      funcId: state.funcId,
    };
    setTimeout(() => {
      $api.common.send.post('function0006',params)
          .then(() => {
            done();
            instance.confirmButtonLoading = false
            $messageBox.success('删除成功', '提示');
            state.funcId = '';
            state.selectRow = {};
            apiTable.value.refresh();
            state.selectNode = [];
            state.apiInfo = null;
          })
          .catch(() => {
            done();
            instance.confirmButtonLoading = false
          });
    }, 100);
  } else {
    $messageBox.warning('请先选择需要删除的数据', '提示');
  }
}

</script>

